<template>
  <el-dialog v-model="dialogVisible" :title="'新增规格'" width="30%">
    <el-form
      ref="formRef"
      :model="specForm"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="名称：" prop="name">
        <el-input v-model="specForm.name" placeholder="请输入名称"></el-input>
      </el-form-item>

      <el-form-item
        v-for="(specValueId, index) in specForm.specValueIds"
        :key="index"
        :label="'规格值：' + (index + 1)"
      >
        <SpecValueSelect
          v-model="specForm.specValueIds[index]"
          style="margin-right: 10px"
        />
        <el-button type="danger" @click="removeSpecValue(index)"
          >删除</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addSpecValue">新增规格值</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addSpecAPI } from "@/apis/goods.js";
import SpecValueSelect from "./SpecValueSelect.vue";

// 状态定义
const dialogVisible = ref(false);
const specForm = ref({
  name: "",
  specValueIds: [],
});

// 引用定义
const formRef = ref(null);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "名称为2-10个字符", trigger: "blur" },
  ],
};

// 事件与方法定义
const emit = defineEmits(["success"]);

const addSpecValue = () => {
  specForm.value.specValueIds.push("");
};

const removeSpecValue = (index) => {
  specForm.value.specValueIds.splice(index, 1);
};

const onSubmit = async () => {
  await formRef.value.validate();
  await addSpecAPI(specForm.value);
  ElMessage.success("添加成功");
  dialogVisible.value = false;
  emit("success");
};

// 暴露给外部的方法
const open = () => {
  dialogVisible.value = true;
  specForm.value = {
    name: "",
    specValueIds: [],
  };
};

defineExpose({
  open,
});
</script>